package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    /**
     * 拦截资源之前
     * @param request
     * @param response
     * @param handler
     * @return boolean  返回true则表示放行,反之不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return HandlerInterceptor.super.preHandle(request, response, handler);
        //获取登录用户
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        log.info("拦截处理器: 获取后端登录用户 :  {}" , employeeId);
        if (employeeId != null){
            //后端用户已登录,放行
            //放入数据到线程数据变量中,使用同一个线程的类中都可以获取
            BaseContext.setThreadLocal(employeeId);
            return true;
        }
        Long userId = (Long) request.getSession().getAttribute("user");
        log.info("拦截处理器: 获取前端登录用户 :  {}" , userId);
        if (userId != null){
            //前端用户已登录,放行
            BaseContext.setThreadLocal(userId);
            return true;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //没有登录,不放行
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
